package com.choosefine.it.basedata.service;

import com.choosefine.it.basedata.dao.TeamTypeMapper;
import com.choosefine.it.basedata.model.TeamType;
import com.choosefine.it.basedata.model.vo.TeamTypeClassFindVO;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.utils.PagedResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("teamtypeService")
public class TeamTypeService {
	@Resource
	private TeamTypeMapper teamtypemapper;

	public int deleteByPrimaryKey(Integer id) {

		int num = 0;
		TeamType deleteTeamTypeUp = teamtypemapper.selectByPrimaryKey(id);
		TeamType deleteTeamType = teamtypemapper.selectByPrimaryKey(id);
		if(null != deleteTeamTypeUp){
			deleteTeamTypeUp.setSortNum(deleteTeamType.getSortNum());
			num += teamtypemapper.updateByPrimaryKeySelective(deleteTeamTypeUp);
		}
		num += teamtypemapper.deleteByPrimaryKey(id);
		return num;
	}

	public TeamType findByPrimaryKey(Integer id) {

		return teamtypemapper.selectByPrimaryKey(id);
	}

	public List<TeamType> selectAll() throws BusinessException {
		List<TeamType> getList = teamtypemapper.selectAll();
		return teamTypeOrder(getList);
	}

	public PageInfo<TeamType> getTeamTypeListByFather(Integer fatherId,Integer pageNum,Integer pageSize) throws BusinessException {
		pageNum = pageNum == null?1:pageNum;
		pageSize = pageSize == null?10:pageSize;
		List<TeamType> returnList =  teamTypeOrder(teamtypemapper.getTeamTypeListByFather(fatherId));
		if(returnList.size()==0){
			return new PageInfo<TeamType>();
		}
		int start = (pageNum-1) * pageSize;
		if (start > returnList.size()) {
			return new PageInfo<TeamType>();
		}
		int end = pageNum * pageSize;
		end = end > returnList.size()?returnList.size()-1:end;
		return new PageInfo<TeamType>(returnList.subList(start, end));
	}
	
	public List<TeamType> getTeamTypeListByFather(Integer fatherId) throws BusinessException {
		List<TeamType> returnList =  teamTypeOrder(teamtypemapper.getTeamTypeListByFather(fatherId));
		if(returnList.size()==0){
			return new ArrayList<TeamType>();
		}
		return returnList;
	}

	public int insert(TeamType record) throws BusinessException {
		Map<String,Object> checkMap = new HashMap<>();
		checkMap.put("name", record.getName());
		checkMap.put("superId", record.getSuperid());
		int count = teamtypemapper.checkTeamTypeInsert(checkMap);
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		Map<String,Object> map = new HashMap<>();
		Map<String,Object> mapNew = new HashMap<>();
		int num = 0;
		map.put("sortNum", 0);
		map.put("superid", record.getSuperid());
		mapNew.put("superid", record.getSuperid());
		TeamType lastTeamType = teamtypemapper.selectTeamTypeBySortNum(map);
		if(null != lastTeamType){
			record.setSortNum(-1);
			num += teamtypemapper.insertSelective(record);
			mapNew.put("sortNum", -1);
			record = teamtypemapper.selectTeamTypeBySortNum(mapNew);
			lastTeamType.setSortNum(record.getId());
			record.setSortNum(0);
			num += teamtypemapper.updateByPrimaryKeySelective(record);
			num += teamtypemapper.updateByPrimaryKeySelective(lastTeamType);
		}else{
			record.setSortNum(0);
			num += teamtypemapper.insertSelective(record);
		}
		return num;
	}

	public int update(TeamType record) {

		return teamtypemapper.updateByPrimaryKey(record);
	}

	public int insertByMap(Map<String, Object> record) {

		return teamtypemapper.insert(record);
	}

	public int updateByMap(Map<String, Object> record) {

		return teamtypemapper.update(record);
	}

	public PageInfo<TeamType> findAllByPage(Map<String, Object> t,
			Integer pageNum, Integer pageSize) {
		pageNum = pageNum == null?1:pageNum;
		pageSize = pageSize == null?10:pageSize;
		PageHelper.startPage(pageNum, pageSize);
		return PagedResult.toPageInfo(teamtypemapper.selectAll());
	}
	
	public PageInfo<TeamType> getTeamTypeListByName(Map<String, Object> map,Integer pageNum,Integer pageSize)
	{
		pageNum = pageNum == null?1:pageNum;
		pageSize = pageSize == null?10:pageSize;
		PageHelper.startPage(pageNum, pageSize);
		return PagedResult.toPageInfo(teamtypemapper.getTeamTypeListByName(map));
	}
	
	public int TeamTypeOrderUp(Integer fromId,Integer toId){
		int num = 0;
		TeamType fromTeamType = null;
		fromTeamType = teamtypemapper.selectByPrimaryKey(fromId);
		Map<String,Object> fromTeamTypeMap = new HashMap<>();
		fromTeamTypeMap.put("sortNum", fromId);
		fromTeamTypeMap.put("superid", fromTeamType.getSuperid());
		
		Map<String,Object> fromTeamTypeUpMap= new HashMap<>();
		fromTeamTypeUpMap.put("sortNum", fromId);
		fromTeamTypeUpMap.put("superid", fromTeamType.getSuperid());
		
		Map<String,Object> toTeamTypeUpMap= new HashMap<>();
		toTeamTypeUpMap.put("sortNum", toId);
		toTeamTypeUpMap.put("superid", fromTeamType.getSuperid());
		
		TeamType fromTeamTypeUp = null;
		TeamType toTeamTypeUp = null;
		fromTeamTypeUp = teamtypemapper.selectTeamTypeBySortNum(fromTeamTypeUpMap);
		toTeamTypeUp = teamtypemapper.selectTeamTypeBySortNum(toTeamTypeUpMap);
		if(toTeamTypeUp == null){
			fromTeamTypeUp.setSortNum(fromTeamType.getSortNum());
			fromTeamType.setSortNum(toId);
		}else{
			fromTeamTypeUp.setSortNum(fromTeamType.getSortNum());
			fromTeamType.setSortNum(toId);
			toTeamTypeUp.setSortNum(fromId);
		}
		if(null != toTeamTypeUp){
			num += teamtypemapper.updateByPrimaryKeySelective(toTeamTypeUp);
		}
		num += teamtypemapper.updateByPrimaryKeySelective(fromTeamType);
		num += teamtypemapper.updateByPrimaryKeySelective(fromTeamTypeUp);
		return num;
	}
	public int TeamTypeOrderDown(Integer fromId,Integer toId){
		int num = 0;
		TeamType fromTeamType = null;
		fromTeamType = teamtypemapper.selectByPrimaryKey(fromId);
		Map<String,Object> fromTeamTypeMap = new HashMap<>();
		fromTeamTypeMap.put("sortNum", fromId);
		fromTeamTypeMap.put("superid", fromTeamType.getSuperid());
		
		Map<String,Object> fromTeamTypeUpMap= new HashMap<>();
		fromTeamTypeUpMap.put("sortNum", fromId);
		fromTeamTypeUpMap.put("superid", fromTeamType.getSuperid());
		
		Map<String,Object> toTeamTypeMap= new HashMap<>();
		toTeamTypeMap.put("sortNum", fromId);
		toTeamTypeMap.put("superid", fromTeamType.getSuperid());
		
		TeamType fromTeamTypeUp = null;
		TeamType toTeamType = null;
		fromTeamTypeUp = teamtypemapper.selectTeamTypeBySortNum(fromTeamTypeUpMap);
		toTeamType = teamtypemapper.selectByPrimaryKey(toId);
		if(fromTeamTypeUp == null){
			fromTeamType.setSortNum(toTeamType.getSortNum());
			toTeamType.setSortNum(fromId);
		}else{
			fromTeamTypeUp.setSortNum(fromTeamType.getSortNum());
			fromTeamType.setSortNum(toTeamType.getSortNum());
			toTeamType.setSortNum(fromId);
		}
		if(null != fromTeamTypeUp){
			num += teamtypemapper.updateByPrimaryKeySelective(fromTeamTypeUp);
		}
		num += teamtypemapper.updateByPrimaryKeySelective(fromTeamType);
		num += teamtypemapper.updateByPrimaryKeySelective(toTeamType);
		return num;
	}
	
	/**
	 * 用于返回根据 sortNum 排序后的，列表
	 *  juchengyang 2017年2月16日
	 * @throws Exception 
	 */
	public List<TeamType> teamTypeOrder(List<TeamType> getList) throws BusinessException{
		int size = getList.size();
		if(getList.size()==0){
			return new ArrayList<TeamType>();
		}
		checkList(getList);
		if(getList.size()==0){
			return null;
		}
		List<TeamType> returnList = new ArrayList<>();
		for(TeamType temp:getList){
			//最后一位 sortNum 为0
			if(0 == temp.getSortNum()){
				returnList.add(temp);
			}
		}
		TeamType tempTeamType = returnList.get(0);
		while(returnList.size()<size){
			for(int i = 0; i<size; i++){
				if(tempTeamType.getId().equals(getList.get(i).getSortNum())){
					returnList.add(getList.get(i));
					tempTeamType = getList.get(i);
				}
			}
		}
		for(int i=0; i<size/2; i++){
			TeamType tempProjecType = returnList.get(i);
			returnList.set(i, returnList.get(size-i-1));
			returnList.set(size-i-1, tempProjecType);
		}
		return returnList; 
	}
	/**
	 * add by juchengyang 2017/2/17
	 * @throws BusinessException 
	 */
	public int updateByPrimaryKeySelective(TeamType record) throws BusinessException{
		Map<String,Object> checkMap = new HashMap<>();
		checkMap.put("name", record.getName());
		checkMap.put("superId", record.getSuperid());
		int count = teamtypemapper.checkTeamTypeInsert(checkMap);
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		return teamtypemapper.updateByPrimaryKeySelective(record);
	}

	/*
	 * 数据校验
	 */
	public void checkList (List<TeamType> list) throws BusinessException{
    	Map<Integer, Integer> keyMap = new HashMap<Integer, Integer>();
        Map<Integer, Integer> nextMap = new HashMap<Integer, Integer>();
        for( TeamType n: list){
        	if (nextMap.containsKey(n.getSortNum())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：next重复");
            }
        	if (n.getSortNum().equals(n.getId())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：指向自己");
            }
        	keyMap.put(n.getId(), n.getSortNum());
            nextMap.put(n.getSortNum(), 0);
        }
        if(!nextMap.containsKey(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("数据出错：不存在0（最后一位标识）");
        }
        for (TeamType n : list) {
            Integer next = keyMap.get(n.getId());
            if (next.equals(0)) {
            	if(!nextMap.containsKey(n.getId()) && nextMap.size()>1){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("没有指向最后一位的");
            	}
            	if(nextMap.get(next).equals(1)){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("数据出错，最后一位不唯一");
            	}else{
            		nextMap.put(next, 1);
            	}
            	
            } else {
            	if(keyMap.containsKey(next)){
	            	if(nextMap.get(next).equals(1)){
	            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//	            		logger.info("数据出错，"+next+"重复");
	            	}else{
	            		nextMap.put(next, 1);
	            	}
            	}else{
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info(next+" 没有对应的 id");
            	}
            }

        }
        if(nextMap.containsValue(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("next 有无效值");
        }
    }

	/**
	 * @Description：根据班组类目id查询所有班组类别（陈健）
	 * @Author：chenjian
	 * @Create Date：2017年2月18日
	 * @param：
	 * @return：
	 */
	public List<TeamTypeClassFindVO> getTeamTypeSecList(Integer fatherId) {
		return teamtypemapper.getTeamTypeSecList(fatherId);
	}
}
